use std::env;

use ane_system::{
    dao::{Dept, DeptDo, Resource, Role, RoleVo, User},
    entity::{sys_dept, sys_resource, sys_role, sys_role_resource, sys_user, sys_user_role},
};
use sea_orm::{sea_query::MysqlQueryBuilder, ColumnTrait, JoinType, QueryTrait};
use sea_orm::{Database, DbConn, EntityTrait, QueryFilter, QuerySelect};
use sea_orm::{Related, RelationDef, RelationTrait};

async fn get_db() -> DbConn {
    dotenv::dotenv().ok();
    let databaseurl = env::var("DATABASEURL").unwrap();
    Database::connect(databaseurl).await.unwrap()
}

#[tokio::main]
#[test]
async fn test() {
    let db = get_db().await;
    ane_system::Mutation::init_db(&db).await.unwrap();
}

#[tokio::main]
#[test]
async fn test_user() {
    let conn = get_db().await;
    // let user = User::list(&conn, 0, 3, Some(1), None, None).await.unwrap();
    // let s = User::get_detail_by_id(&conn, 1, None, false).await.unwrap();
    let s = User::get_resource(&conn, 1).await.unwrap();
    println!(" {s:?}")
}

#[tokio::main]
#[test]
async fn test_role() {
    let conn = get_db().await;
    // Role::list::<RoleVo>(&conn, 0, 50).await.unwrap();
    let res = ane_system::casbin_policies(&conn, None, None)
        .await
        .unwrap();
    println!("{res:?}");
}

#[tokio::main]
#[test]
async fn test_dept() {
    let conn = get_db().await;
    // let dept = DeptDo {
    //     parent_id: Some(7),
    //     dept_name: "Ane".to_owned(),
    //     phone: Some("1515****190".to_owned()),
    //     email: Some("lthee12@hotmail.com".to_owned()),
    //     description: None,
    //     order_num: Some(0),
    //     status: true,
    // };
    // Dept::update(&conn, 6, dept).await.unwrap();
    let tree = Resource::get_role(&conn, 3).await.unwrap();
    println!("{tree:#?}");
}

#[test]
fn test_sql() {
    let sql = sys_user::Entity::find()
        .select_only()
        .column(sys_resource::Column::Path)
        .column(sys_role_resource::Column::Method)
        .join(
            JoinType::InnerJoin,
            <sys_user::Entity as Related<sys_user_role::Entity>>::to(),
        )
        .join(
            JoinType::InnerJoin,
            <sys_user_role::Entity as Related<sys_role::Entity>>::to(),
        )
        .join(
            JoinType::InnerJoin,
            sys_role::Relation::SysRoleResource.def(),
        )
        .filter(sys_resource::Column::Status.eq(true))
        .filter(sys_role::Column::Status.eq(true))
        .filter(sys_user::Column::UserId.eq(1));

    println!("{}", sql.build(sea_orm::DatabaseBackend::MySql).to_string());
}
